//
//  ExWebViewViewController.m
//  OC-Example
//
//  Created by apang on 2018/7/31.
//  Copyright © 2018年 apang.men All rights reserved.
//

#import "ExWebViewViewController.h"
#import <WebKit/WebKit.h>
@interface ExWebViewViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView * webView;
@end

@implementation ExWebViewViewController
- (WKWebView *)webView {

    if (!_webView) {
//
        WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
//        config.preferences.javaScriptEnabled = YES;
//        config.preferences.javaScriptCanOpenWindowsAutomatically =  YES;
        [config.userContentController addScriptMessageHandler:self name:@"jsTOoc"];
        [config.userContentController addScriptMessageHandler:self name:@"cap"];
        [config.userContentController addScriptMessageHandler:self name:@"sendToken"];
        WKUserScript * tmpjs = [[WKUserScript alloc] initWithSource:@"document.onselectionchange = () =>{ var range=window.getSelection().toString();console.log(range);if(range.length>0){window.webkit.messageHandlers.cap.postMessage(range);}};" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [config.userContentController addUserScript:tmpjs];
        
        NSString * logJSString = @"var console = {};\
        console.log = function (message) {\
            window.webkit.messageHandlers['logger'].postMessage(message)\
        };\
        console.info = function (message) {\
            window.webkit.messageHandlers['logger'].postMessage(message)\
        };";
        WKUserScript * logJS = [[WKUserScript alloc] initWithSource:logJSString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [config.userContentController addUserScript:logJS];
        [config.userContentController addScriptMessageHandler:self name:@"logger"];
        
        //MARK: 监听滚动
        [config.userContentController addScriptMessageHandler:self name:@"_scrollEvent"];
        NSString * scrollJSStr = @"\
        window.onscroll = function() {\n \
            var scrollTop = document.documentElement.scrollTop || document.body.scrollTo\n \
            var height = document.documentElement.offsetHeight\n \
            window.webkit.messageHandlers._scrollEvent.postMessage({'offsetHeight':scrollTop, 'height':height})\n \
            console.log(scrollTop,height)\n \
        } \
        ";
        WKUserScript * scrollJS = [[WKUserScript alloc] initWithSource:scrollJSStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [config.userContentController addUserScript:scrollJS];
        
        _webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];

//        _webView = [[WKWebView alloc] initWithFrame:CGRectZero];

        _webView.UIDelegate = self;

        _webView.navigationDelegate = self;

        [self.view addSubview:_webView];
        
        [_webView setTranslatesAutoresizingMaskIntoConstraints:NO];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[_webView]-(0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_webView)]];

        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[_webView]-(0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_webView)]];
    }

    return _webView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.title = @"网页";
    _url = [NSURL URLWithString:@"https://www.baidu.com/s?wd=any"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if(!_url){

        NSString * filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"Resource/html"];

        _url = [NSURL fileURLWithPath:filePath];
    }

    NSURLRequest * request = [NSURLRequest requestWithURL:_url];

    [self.webView loadRequest:request];
    if (@available(iOS 9.0, *)) {
        NSLog(@"%@",[WKWebsiteDataStore allWebsiteDataTypes]);
    }
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"jsTOoc"]) {
        NSLog(@"%@:%@",message.name,message.body);
        NSString * js = [NSString stringWithFormat:@"ocTOjs(\"%@\")",message.body];
        __weak typeof(self) weakSelf = self;
        [_webView evaluateJavaScript:js completionHandler:^(id _Nullable res, NSError * _Nullable error) {
            NSLog(@"console:%@",res);
            [weakSelf.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:res]]];
        }];
    }else if ([message.name isEqualToString:@"cap"]){
        NSLog(@"%@:%@",message.name,message.body);
    }else if ([message.name isEqualToString:@"logger"]) {
        NSLog(@"console.log:%@",message.body);
    } else if ([message.name isEqualToString:@"_scrollEvent"]){
        NSLog(@"method:%@ \n message:%@",message.name, message.body);
    } else {
        NSLog(@"method:%@ \n message:%@",message.name, message.body);
    }
}

- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{

    NSLog(@"createWebViewWithConfiguration");
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"didFinishNavigation");
    [webView evaluateJavaScript:@"document.cookie" completionHandler:^(id _Nullable res, NSError * _Nullable error) {
        NSLog(@"console:%@   error:%@",res, error);
    }];
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"console:%@",message);
    completionHandler();
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    NSLog(@"confirm：%@",message);
    completionHandler(NO);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
